package com.fudan.backend.interceptor;

import com.fudan.backend.exception.BaseException;
import com.fudan.backend.pojo.statics.UserRole;
import com.fudan.backend.exception.RetCode;
import com.fudan.backend.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token").toString();
        //已通过LoginInterceptor验证token合法性，后直接解码token
        //验证当前用户权限（判断当前用户角色）
        int role = JwtUtil.getRole(token);
        if(role != UserRole.Admin){//非管理员
            RetCode code = RetCode.UNAUTHORIZED_REQUEST;
            throw new BaseException(code.getCode(), code.getMessage());
        }
        return true;
    }
}
